<template>
	<view class="container">
		<!-- 顶部导航 -->
		<!-- <topbar :title="paper_name" :scrollTop="scrollTop"></topbar> -->

		<!-- <tui-navigation-bar splitLine @init="initNavigation" @change="opacityChange" :scrollTop="scrollTop" title="NavBar自定义导航栏" backgroundColor="#fff" color="#333">
      <view class="tui-header-icon" :style="{ marginTop: top + 'px' }"><tui-icon name="arrowleft" :color="opacity > 0.85 ? '#333' : '#fff'" @click="back"></tui-icon></view>
    </tui-navigation-bar> -->
		<!-- <view class="tui-header-bg"><image src="/static/componentBg.png" class="tui-header-img"></image></view> -->
		<!-- <tui-navigation-bar  @init="initNavigation" :title="paper_name" @change="opacityChange" :scrollTop="scrollTop" :isOpacity="false" backgroundColor="#fff" color="#333">
      <view class="tui-header-icon" :style="{ marginTop: top + 'px' }"><tui-icon name="arrowleft" color="#333" @click="back"></tui-icon></view>
    </tui-navigation-bar> -->

		<!-- 答题组件 -->
		<kzquestion v-show="result == null" 
			ref="comQuestion"
			mode="EXAM" 
			:title="paper_name" 
			:questions="questions" 
			:configs="configs" 
			:limit_time="limit_time"
			:isPreventSwitchScreen="isPreventSwitchScreen"
			:switchScreenCount="switchScreenCount"
			@submitQuestion="submitQuestion"
			@returntime = "returntime"
			>
		</kzquestion>

		<!-- 成绩组件 -->
		<kzgraderesult :course_id="course_id"  v-show="result != null" :score="score" :gradeResult="result" ref="gradeResult"
			:examMode="exam_mode"></kzgraderesult>

		<!-- toast提示 -->
		<!-- <tui-toast ref="toast"></tui-toast> -->

		<!-- 登录组件 -->
		<login ref="login" @succ="succ"></login>


	</view>
</template>

<script>
	import kzquestion from '@/components/kz-question/kz-question.vue';
	import kzgraderesult from '@/components/kz-grade-result/kz-grade-result.vue';

	import { getQuestionList ,submitQuestionList } from '@/api/index.js'
	export default {
		components: { kzquestion , kzgraderesult },
		data() {
			return {
				// 顶部栏
				// scrollTop: 0,
				// 试卷
				// user: this.utils.getData('user'),
				paper_id: 0,
				paper: null,
				paper_name: '试卷答题中',
				questions: [],
				configs: {},
				start_time: 0,
				limit_time: 1800,
				total: 0,
				// 考试成绩
				result: null,
				score: 0,
				// 考场
				room_id: 0,
				room_grade_id: 0,
				exam_mode: 'PAPER',
				paper_mode: 'RANDOM',
				// 题库
				cate: null,


				isSubmit: false,
				//切屏记录
				isFirstShow: true,
				// 是否防切屏
				isPreventSwitchScreen: false,
				switchScreenCount: 0,
				switchScreenSecond: 0,
				curretSwitchScreenCount: 0,
				// currentSwitchScreenSecond: 0,
				switchScreenTimestamp: 0,
				course_id:0, //教材id
				chapter_id:0,//章节id
				timestamp:0, //开始答题时间
				residueTime:{}, //答题剩余时间
			}
		},
		onShow() {
			//获取打开题库的当前时间 (秒级)
			this.timestamp = Math.floor(Date.now() / 1000);
			//判断是否登录
			if (uni.getStorageSync('token')) {
				this.isLogin = true
			} else {
				  
				this.$nextTick(() => {
					this.$refs.login.modal = true;
				})
			}
			if (this.isFirstShow) {
				this.isFirstShow = false
			} else {
				if (this.isPreventSwitchScreen) {
					// 切屏时间
					let switchScreenSecond = parseInt((Date.now() - this.switchScreenTimestamp) / 1000)
					// 超过切屏认定时间
					if (switchScreenSecond >= this.switchScreenSecond) {
						this.curretSwitchScreenCount++
						// 超过切屏次数
						if (this.curretSwitchScreenCount >= this.switchScreenCount) {
							// 结束考试，强制交卷
							this.utils.toast('切屏超过次数，考试结束', 'error', 5000)
							this.$refs.comQuestion.submit()
							this.submitQuestion([])
						}
					}
				}
			}

			// console.log('onShow', this.curretSwitchScreenCount)
		},
		onHide() {
			if (this.isPreventSwitchScreen) {
				// 当前时间戳
				this.switchScreenTimestamp = Date.now()
			}

			// console.log('onHide', this.switchScreenTimestamp)
		},
		onLoad(options) {
			this.course_id = options.course_id
			//获取试题
			this.getQuestion({course_id:this.course_id})
			//题目列表传参  是哪套题
			// this.paper_id = options.id
			// this.room_id = options.room_id ? options.room_id : 0

			// this.ajax()
			// if (this.room_id) {
			// 	this.getQuestion()
			// }
			
		},
		onBackPress(e) {
			if (!this.isSubmit) {
				if (e.from == "backbutton") {
					let message = '您尚未交卷，离开本页面将没有成绩哦'
					if (this.room_id) {
						message = '您尚未交卷，离开本页面将没有成绩且失去本次考试资格哦'
					}

					uni.showModal({
						title: '提示',
						content: message,
						success: (res) => {
							if (res.confirm) {
								uni.navigateBack({
									delta: 1
								});
							}
						}
					});

					return true; //阻止默认返回行为
				}
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop
		},
		methods: {
			succ(){
				this.getQuestion({course_id:this.course_id})
			},
			// 答题剩余时间
			returntime(data){
				this.residueTime = data
			},
			// 获取试卷试题
			getQuestion(data) {
				getQuestionList(data).then(res => {
					if (res.data.code == 1) {
						this.questions = res.data.data
						this.chapter_id = res.data.data[0].chapter_id
						// this.total = questions.length
						// this.configs = this.paper.configs	
					}

					// this.paper = res.data.paper
					// this.paper_mode = this.paper.mode
					// this.paper_name = this.paper.title
					// this.limit_time = this.paper.limit_time
					// this.start_time = res.data.start_time
					// this.room_grade_id = res.data.room_grade_id

					// let questions = res.data.questions
					// for (let i in questions) {
					// 	questions[i]['code2'] = false
					// 	console.log('questions[i][score]', questions[i]['score'])
					// 	questions[i]['score'] = this.getSingleScore(questions[i])//, questions[i].kind, questions[i].difficulty
					// 	console.log('questions[i][score]', questions[i]['score'])
					// }

					// this.questions = questions
					// this.total = questions.length
					// this.configs = this.paper.configs					
					
					// 防切屏
					// if (this.paper.is_prevent_switch_screen && this.paper.switch_screen_count && this.paper.switch_screen_second) {
					// 	this.isPreventSwitchScreen = true
					// 	this.switchScreenCount = this.paper.switch_screen_count
					// 	this.switchScreenSecond = this.paper.switch_screen_second
					// }
				})
			},
			// 交卷
			async submitQuestion(paperData) {
				
				if (this.isSubmit) {
					return
				}

				uni.showLoading({
					title: '交卷中'
				})
				// 过滤出 b 数组的所有对象 id 并添加新属性 answer 值为 ''
				const filteredB = this.questions.map(item => ({
				    id: item.id,
				    answer: ''
				}));
				// 创建一个 id 映射表，以便快速查找 paperData.questions 中的元素
				const aMap = new Map(paperData.questions.map(item => [item.id, item]));
				// 遍历数组 b，如果 b 中的元素在 a 中有对应的 id，则用 a 中的元素覆盖它
				const questions = filteredB.map(itemB => aMap.has(itemB.id) ? aMap.get(itemB.id) : itemB);
				
				let data = {
					course_id:this.course_id,
					start_time: this.timestamp, 
					questions: JSON.stringify(questions),
					chapter_id:this.chapter_id
				}
				
				const res = await submitQuestionList(data)
				if(res.data.code == 1){
					uni.hideLoading();
					this.result = res.data.data
					this.score = res.data.data.score
					this.isSubmit = true
				}

			},
			// 计算试题分数
			getSingleScore(question) {
				console.log('paper_mode', this.paper_mode)
				if (this.paper_mode == 'FIX') {
					return question.score
				}

				let kind = question.kind
				let difficulty = question.difficulty
				const configs = this.paper.configs[kind.toLowerCase()]
				if (configs && configs['use_difficulty']) {
					return configs['difficulty'][difficulty.toLowerCase()]['score']
				}
				return configs['score']
			},

			/**
			 * 返回上一页
			 */
			goBack() {
				const pages = getCurrentPages();
				if (pages && pages.length > 0) {
					const firstPage = pages[0];
					if (pages.length == 1 && (!firstPage.route || firstPage.route != "pages/index/index")) {
						uni.reLaunch({
							url: "/pages/index/index",
						});
					} else {
						uni.navigateBack({
							delta: 1,
						});
					}
				} else {
					uni.reLaunch({
						url: "/pages/index/index",
					});
				}
			},
		}
	}
</script>

<style>
	page {
		height: 100%;
	}

	.container {
		padding-bottom: 120rpx;
		box-sizing: border-box;
	}

	.tui-header-icon {
		width: 100%;
		position: fixed;
		top: 0;
		padding: 0 12rpx;
		display: flex;
		align-items: center;
		height: 32px;
		transform: translateZ(0);
		z-index: 99999;
		box-sizing: border-box;
	}

	.tui-modal-custom {
		text-align: center;
	}

	.tui-tips-img {
		width: 80rpx;
		height: 80rpx;
		margin-top: 20rpx;
	}

	.tui-modal-custom-text {
		font-size: 30rpx;
		color: #333;
		padding: 30rpx 0 50rpx;
	}
</style>
